package com.lines.chap03;

import lombok.Data;

/**
 * <p>
 * <code>DoubleLinkedList</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-28 16:03
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class DoubleLinkedList {
    private Node head;
    private Node tail;

    public DoubleLinkedList() {
        this.head = null;
        this.tail = null;
    }

    public void insertHead(int data){
        Node node = new Node(data);
        if (head==null){
            head=node;
            tail = node;
        }else {
            node.next=head;
            head.pre=node;
            head=node;
        }
    }
    public void deleteHead(){
        if (head==null){
            return;
        }

        if (head.next==null){
            head=null;
            tail=null;
            return;
        }
        Node newHead = head.next;
        newHead.pre=null;
        head.next=null;
        head=newHead;
    }

    public void deleteTail(){
        if (tail==null){
            return;
        }
        if (tail.pre==null){
            tail=null;
            head=null;
            return;
        }
        Node newTail = tail.pre;
        newTail.next=null;
        tail.pre=null;
        tail=newTail;

    }

    public void deleteData(int data){
        Node node = find(data);
        if (node==null){
            return;
        }
        if (node==head){
            deleteHead();
            return;
        }
        if (node==tail){
            deleteTail();
            return;
        }

        node.pre.next=node.next;
        node.next.pre= node.pre;
    }

    public Node find(int data){
        Node cur = head;
        while (cur!=null){
            if (data==cur.value){
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

    @Data
    private static class Node{
        int value;
        Node next;
        Node pre;

        public Node(int value) {
            this.value = value;
            this.next = null;
            this.pre = null;
        }
    }
}
